package com.app.oasystem.service.impl;


import com.app.oasystem.dto.ActionResult;
import com.app.oasystem.dto.PageGridDto;
import com.app.oasystem.dto.TableDto;
import com.app.oasystem.entity.Record;
import com.app.oasystem.entity.User;
import com.app.oasystem.exception.CommonException;
import com.app.oasystem.mapper.RecordMapper;
import com.app.oasystem.mapper.UserMapper;
import com.app.oasystem.service.RecordService;
import com.app.oasystem.utils.DateUtils;
import com.app.oasystem.utils.TableDtoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 86+
 * @data 2021-04-13
 */

@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {
    @Resource
    RecordMapper recordMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public TableDto getRecordList(PageGridDto pageGridDto) {
        Page<Record> page = new Page<>(pageGridDto.getPage(), pageGridDto.getlimit());
        Page selectPage = new Page();
        Object search = pageGridDto.getSearchCondition().get("search");
        Object userId = pageGridDto.getSearchCondition().get("userId");
        if (null != search) {
            selectPage = recordMapper.selectPage(page, new QueryWrapper<Record>().eq("uid", userId).like("username", search).orderByDesc("begintime"));
            System.out.println("Record List : " + selectPage.getRecords());
        } else {
            Integer role = userMapper.selectOne(new QueryWrapper<User>().eq("id", pageGridDto.getUserId())).getRole();
            if (0 != role) {
                selectPage = recordMapper.selectPage(page, new QueryWrapper<Record>().eq("uid", userId).orderByDesc("begintime"));
            } else {
                selectPage = recordMapper.selectPage(page, new QueryWrapper<Record>().orderByDesc("begintime"));
            }
        }
        return TableDtoUtils.setTableDto(selectPage.getTotal(), selectPage.getRecords());
    }

    /**
     * 注意当前的id主键 是默认的"id"，具体情况根据数据库主键的名称进行修改
     */
    @Override
    public Record getRecordInfoById(Integer id) {
        Record record = new Record();
        try {
            record = recordMapper.selectOne(new QueryWrapper<Record>().eq("uid", id).like("begintime", DateUtils.format(new Date(), "yyyy-MM-dd")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == record) {
            log.error("当前查询的:[{record}]不存在");
        }
        return record;
    }

    /**
     * 注意当前的name 名称 是默认的"name"，具体情况根据数据库对应的名称进行修改
     */
    @Override
    public Record getRecordInfoByName(String recordName) {
        Record record = null;
        try {
            record = recordMapper.selectOne(new QueryWrapper<Record>().eq("name", recordName));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[{record}] 未知异常");
        }
        if (null == record) {
            throw new CommonException("当前查询的:[{record}]不存在");
        }
        return record;
    }

    @Override
    public boolean updateRecord(Record record) {
        int id = 0;
        try {
            id = recordMapper.update(record, new UpdateWrapper<Record>().eq("id", record.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[{record}] 未知异常");
        }
        return id > 0;
    }

    @Override
    public boolean insertRecord(Record record) {
        int id = 0;
        try {
            id = recordMapper.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[{record}] 未知异常");
        }
        return id > 0;
    }

    @Override
    public boolean deleteRecord(Record record) {
        int id = 0;
        try {
            id = recordMapper.deleteById(record.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id > 0;
    }

    @Override
    public Object up(Integer userId) {
        Record record = recordMapper.selectOne(new QueryWrapper<Record>().eq("uid", userId).like("begintime", DateUtils.format(new Date(), "yyyy-MM-dd")));

        if (null == record) {
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", userId));
            Record newRecord = new Record();
            Date beginTime = new Date();
            newRecord.setBegintime(beginTime);
            newRecord.setEndtime(null);
            newRecord.setPhone(user.getPhone());
            newRecord.setUid(userId);
            newRecord.setUsername(user.getUsername());
            String hHmmss = DateUtils.format(new Date(), "HHmmss");
            int num = DateUtils.transferNum(hHmmss);
            if (num <= 80000) {
                newRecord.setStatus(0);
            } else if (num <= 180000) {
                newRecord.setStatus(1);
            } else {
                newRecord.setStatus(3);
                newRecord.setBegintime(new Date());
                newRecord.setEndtime(new Date());
            }
            int insert = recordMapper.insert(newRecord);
            if (insert > 0) {
                return new ActionResult(true, "上班打卡成功", DateUtils.format(beginTime, "yyyy-MM-dd HH:mm:ss"));
            } else {
                return new ActionResult(false, "系统错误，请联系管理员...");
            }
        } else {
            return new ActionResult(false, "打卡失败，您已打卡...");
        }
    }

    @Override
    public Object down(Integer userId) {
        Record record = recordMapper.selectOne(new QueryWrapper<Record>().eq("uid", userId).like("begintime", DateUtils.format(new Date(), "yyyy-MM-dd")));
        Date endtime = record.getEndtime();
        if (null != endtime) {
            return new ActionResult(false, "打卡失败，您已打卡...");
        }
        record.setEndtime(new Date());
        String hHmmss = DateUtils.format(new Date(), "HHmmss");
        int num = DateUtils.transferNum(hHmmss);
        if (num <= 180000) {
            record.setStatus(3);
            int insert = recordMapper.update(record, new UpdateWrapper<Record>().eq("id", record.getId()));
            if (insert > 0) {
                return new ActionResult(true, "下班打卡成功", DateUtils.format(record.getEndtime(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                return new ActionResult(false, "系统错误，请联系管理员...");
            }
        }
        return null;
    }
}
